package com.example.rabbitmq.rpc;

import com.example.rabbitmq.constant.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setPassword(Constants.PASSWORD);
        factory.setUsername(Constants.USERNAME);
        factory.setVirtualHost(Constants.VIRTUALHOST);
        //创建连接
        Connection connection = factory.newConnection();
        //创建通道
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);

        //发送消息
        String msg="hello";
        String correlationId = UUID.randomUUID().toString();
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .correlationId(correlationId)
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .build();
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE, props, msg.getBytes());

        //接收效应
        BlockingQueue<String>response=new ArrayBlockingQueue<>(1);

        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("收到响应");
                if (properties.getCorrelationId().equals(correlationId)){
                    response.offer(new String(body));
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        String result = response.take();
        System.out.println("[客户端接收到响应：]"+result);
    }
}
